package com.jeeplus.modules.act.listener;

import com.google.common.collect.Maps;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.utils.IdGen;
import com.jeeplus.common.utils.SpringContextHolder;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.sys.entity.Role;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.mapper.UserMapper;
import com.jeeplus.modules.sys.utils.LogUtils;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.wxMsg.SendWX;
import com.jeeplus.modules.wxMsg.entity.WxResult;
import org.activiti.engine.TaskService;
import org.activiti.engine.delegate.event.ActivitiEvent;
import org.activiti.engine.delegate.event.impl.ActivitiEntityEventImpl;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.task.IdentityLink;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

public class TaskCompleteListener implements EventHandler {
    protected Logger logger = LoggerFactory.getLogger(getClass());
    private static UserMapper userMapper = SpringContextHolder.getBean(UserMapper.class);
    public static final String wxsend = Global.getConfig("wxsend");
    @Override
    public void handle(ActivitiEvent event) {
        TaskService taskService = SpringContextHolder.getBean(TaskService.class);
        if("1".equals(wxsend)){
            try {
                ActivitiEntityEventImpl eventImpl = (ActivitiEntityEventImpl) event;
                TaskEntity taskEntity = (TaskEntity) eventImpl.getEntity();
                String wxName = "";
                User user = new User();
                //代理人
                String assignee = taskEntity.getAssignee();
                if(!"true".equals(taskEntity.getVariable("saveFlag").toString())){
                    if(assignee.equals(UserUtils.getUser().getLoginName())){
                        HashMap vars = Maps.newHashMap();
                        String taskId = taskEntity.getId();
                        String procInsId = taskEntity.getProcessInstanceId();
                        // 添加意见
                        taskService.addComment(taskId, procInsId, "同意（自动）");
                        vars.put("pass",true);
                        /*vars.put("title",taskEntity.getName());*/
                        taskService.complete(taskEntity.getId(),vars);
                    }else {
                        if(StringUtils.isNotBlank(assignee)){
                            user.setLoginName(assignee);
                            wxName = userMapper.getByLoginName(user).getWxname();
                            System.out.println("下个节点处理人："+assignee);
                            SendWX.send(wxName,"您有一条新的流程待办 ["+taskEntity.getVariables().get("title")+"|"+taskEntity.getName()+"]",taskEntity);
                        }else if(taskEntity.getCandidates() != null){//代理组
                            System.out.println(taskEntity.getCandidates());
                            Set<IdentityLink> identityLinks = taskEntity.getCandidates();
                            for (IdentityLink identityLink : identityLinks) {
                                String groupId = identityLink.getGroupId();
                                Role role = new Role();
                                role.setEnname(groupId);
                                List<User> userList = userMapper.findList(new User(role));
                                if(userList != null && userList.size() >0){
                                    for(User user1 : userList){
                                        user.setLoginName(user1.getLoginName());
                                        wxName = userMapper.getByLoginName(user).getWxname();
                                        SendWX.send(wxName,"您有一条新的流程待办 ["+taskEntity.getVariables().get("title")+"|"+taskEntity.getName()+"]",taskEntity);
                                    }
                                }

                            }
                        }else {
                            WxResult wxResult = new WxResult();
                            wxResult.setId(IdGen.uuid());
                            wxResult.setCreateDate(new Date());
                            wxResult.setErrcode("1001");
                            wxResult.setErrmsg("无代理人/组");
                            wxResult.setTaskEntity(taskEntity);
                            wxResult.setToUser("");
                            LogUtils.saveWxSendLog(wxResult);
                        }
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }


}
